﻿////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// <copyright>Copyright 2008-2011 Andreas Huber Doenni</copyright>
// Distributed under the GNU General Public License version 2 (GPLv2).
// See accompanying file License.txt or copy at http://phuse.codeplex.com/license.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

namespace Phuse.Mime
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics.CodeAnalysis;
    using System.IO;
    using System.Text;

    using Phuse.IO;

    /// <summary>Represents an entity body (see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a> 2.4. &amp;
    /// 2.6.) with text content (see <a href="http://www.ietf.org/rfc/rfc2046.txt">RFC 2046</a> 4.1.).</summary>
    /// <threadsafety static="true" instance="false"/>
    public sealed class TextBody : Body<TextBody>
    {
        private static readonly string LowercaseYes = DelSP.Yes.ToString().ToLowerInvariant();
        private string content = string.Empty;
        private Format format = Format.Flowed;

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        /// <summary>Initializes a new instance of the <see cref="TextBody"/> class.</summary>
        /// <param name="subtype">The subtype of the text body, usually one of the <see cref="TextSubtypeNames"/>
        /// members.</param>
        /// <exception cref="ArgumentException"><paramref name="subtype"/> is <c>null</c> or empty.</exception>
        public TextBody(string subtype) : base(subtype)
        {
        }

        /// <summary>Gets or sets the body content.</summary>
        /// <remarks>The default value is <see cref="string.Empty">string.Empty</see>, which is set during construction
        /// and when the parser does not find valid content.</remarks>
        /// <exception cref="ArgumentNullException">Attempted to set to <c>null</c>.</exception>
        public string Content
        {
            get
            {
                return this.content;
            }

            set
            {
                if (value == null)
                {
                    throw new ArgumentNullException("value");
                }

                this.content = value;
            }
        }

        /// <summary>Gets or sets the format of the text body.</summary>
        public Format Format
        {
            get
            {
                return this.format;
            }

            set
            {
                this.format = value;
            }
        }

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        internal TextBody(FallbackReason fallbackReason) : base(TextSubtypeNames.Plain, fallbackReason)
        {
        }

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        /// <summary>See <see cref="Body.WriteTo(Stream, Action{IEnumerable{HeaderField}, bool})"/>.</summary>
        [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", Justification = "Not callable from external code, CA bug?")]
        protected internal sealed override void WriteTo(
            Stream stream, Action<IEnumerable<HeaderField>, bool> writeHeaderFieldsCallback)
        {
            var utf8Encoded = Encoding.UTF8.GetBytes(this.content);
            var isBase64 = Base64Stream.GetEncodedLength(utf8Encoded.Length) <
                QuotedPrintableStream.GetEncodedLength(utf8Encoded, 0, utf8Encoded.Length, false);
            var contentTransferEncoding =
                isBase64 ? ContentTransferEncodingNames.Base64 : ContentTransferEncodingNames.QuotedPrintable;
            var fields = this.GetRequiredHeaderFields(
                MediaTypeNames.Text, this.GetAdditionalParameters(), contentTransferEncoding);
            writeHeaderFieldsCallback(fields, true);

            if (stream != null)
            {
                // FixLineEndingsStream ensures that line-endings are correct first.
                using (var guard = ScopeGuard.Create(new ForwardingStream(stream)))
                using (var encodingStream = isBase64 ?
                    (Stream)new Base64Stream(guard.Resource) : new QuotedPrintableStream(guard.Resource, false))
                using (var flowedStream = this.format == Format.Fixed ? encodingStream : new FlowedStream(encodingStream))
                using (var fixingStream = new FixLineEndingsStream(flowedStream))
                {
                    guard.Dismiss();
                    fixingStream.Write(utf8Encoded, 0, utf8Encoded.Length);
                }
            }
        }

        private IEnumerable<KeyValuePair<string, string>> GetAdditionalParameters()
        {
            yield return new KeyValuePair<string, string>(ContentTypeParameterNames.CharSet, Encoding.UTF8.WebName);
            yield return new KeyValuePair<string, string>(
                ContentTypeParameterNames.Format, this.Format.ToString().ToLowerInvariant());

            if (this.Format == Format.Flowed)
            {
                yield return new KeyValuePair<string, string>(ContentTypeParameterNames.DelSp, LowercaseYes);
            }
        }
    }
}
